package org.myhibernate.util;

import java.lang.reflect.Field;

import org.myhibernate.entity.UserEntity;

public class EntityUtils 
{
	public static String getEntityMappingXml(Class cls,String idFieldName)
	{
		XML mappingXml=new XML("mapping");
		mappingXml.addAttribute("name", cls.getSimpleName());
		mappingXml.addAttribute("table", cls.getSimpleName().toUpperCase());
		XML idXml=new XML("id"); 
		idXml.addAttribute("field", idFieldName);
		mappingXml.addChild(idXml);
		Field[] fields=cls.getDeclaredFields();
		Field field=null;
		for (int i = 0; i < fields.length; i++) 
		{
			field=fields[i];
			XML propertyXml=new XML("property");
			mappingXml.addChild(propertyXml);
			String fName=field.getName();
			propertyXml.addAttribute("field", fName);
			propertyXml.addAttribute("column", fName.toUpperCase());
			propertyXml.addAttribute("get", "get"+fName.substring(0,1).toUpperCase()+fName.substring(1));
			propertyXml.addAttribute("set", "set"+fName.substring(0,1).toUpperCase()+fName.substring(1));			
		}
		//System.out.println(mappingXml);
		return mappingXml.toString();
	}
	public static String getEntityCreateTableSql(Class cls,String idFieldName)
	{
		StringBuffer buffer=new StringBuffer();
		String className=cls.getSimpleName().toUpperCase();
		idFieldName=idFieldName.toUpperCase();
		buffer.append("drop table "+className+";");
		buffer.append("\n");
		buffer.append("create table "+className+"(");
		buffer.append("\n");
		Field[] fields=cls.getDeclaredFields();
		Field field=null;
		String fieldName="",comman=",",fieldType="";
		int length=fields.length;
		for (int i = 0; i < length; i++)
		{
			if (i==length-1) {
				comman="";
			}
			field=fields[i];
			fieldName=field.getName().toUpperCase();
			fieldType=field.getType().getSimpleName().toLowerCase();
			if ("string".equals(fieldType)) 
			{
				if (idFieldName.equals(fieldName))
				{
					buffer.append(fieldName+" varchar(50) primary key not null"+comman);
				} else
				{
					buffer.append(fieldName+" varchar(100) "+comman);
				}
			}else if ("char".equals(fieldType)) 
			{
					buffer.append(fieldName+" char(1) "+comman);
			}else if ("boolean".equals(fieldType)) 
			{
					buffer.append(fieldName+" varchar(5) "+comman);
			}else if ("int".equals(fieldType)||"integer".equals(fieldType)||"long".equals(fieldType)) 
			{
				buffer.append(fieldName+" number(20,2) "+comman);
			}else
			{
				buffer.append(fieldName+" XXX "+comman);
			}

			buffer.append("\n");
		}//end for
		buffer.append(");");
		return buffer.toString();
	}
	public static void main(String[] args) 
	{
		Class cls=UserEntity.class;
		String idFieldName="id";
		System.out.println(getEntityMappingXml(cls,idFieldName));
		System.out.println();
		System.out.println("###########################################################################");
		System.out.println();
		System.out.println(getEntityCreateTableSql(cls,idFieldName));
		
	}
}
